import { apiService, type ApiResponse } from './api'

export interface User {
  id: string
  username: string
  email: string
  createdAt?: string
}

export interface LoginData {
  email: string
  password: string
}

export interface RegisterData {
  username: string
  email: string
  password: string
}

export interface AuthResponse {
  token: string
  user: User
}

class AuthService {
  // 用户注册
  async register(data: RegisterData): Promise<ApiResponse<AuthResponse>> {
    const response = await apiService.post<AuthResponse>('/api/auth/register', data)
    
    if (response.success && response.data) {
      apiService.setToken(response.data.token)
    }
    
    return response
  }

  // 用户登录
  async login(data: LoginData): Promise<ApiResponse<AuthResponse>> {
    const response = await apiService.post<AuthResponse>('/api/auth/login', data)
    
    if (response.success && response.data) {
      apiService.setToken(response.data.token)
    }
    
    return response
  }

  // 获取用户信息
  async getProfile(): Promise<ApiResponse<{ user: User }>> {
    return apiService.get<{ user: User }>('/api/auth/profile')
  }

  // 用户登出
  logout() {
    apiService.clearToken()
  }

  // 检查是否已登录
  isAuthenticated(): boolean {
    return !!localStorage.getItem('auth_token')
  }

  // 获取当前token
  getToken(): string | null {
    return localStorage.getItem('auth_token')
  }
}

export const authService = new AuthService()